/**
 * @author: quantm.tb@gmail.com/quandaso
 * @module:
 * @version:
 * @date: 11/11/13 2:12 PM 
 */
(function($){

    $.fn.create_type_ahead_input = function(fn){
        if(!this.length)
            return _W("*fn: create_type_ahead_input(): " + this.selector + " is n/a!");

        if(!this.is("input"))
            return _W("*fn: create_type_ahead_input(): " + this.selector + " is not a input!");

        var self = this;
        var search_url = self.attr("data-search-ajax");
        if(!search_url )
            return _W("*fn: create_type_ahead_input(): Missing data-search-ajax  " + this.selector);

        var auto_suggest_list = [];
        self.typeahead({source: auto_suggest_list});
        self.keyup(function(e){
            if(e.which == 13){
                if(typeof fn == "function")
                    fn.call(self, self.val());
                return;
            }
            var data = {key: self.val()};
            $.post(search_url, data)
                .done(function(d){
                    var r = $.parseJSON(d);
                    for(var i in r){
                        if(auto_suggest_list.indexOf(r[i]) == -1){
                            auto_suggest_list.push(r[i]);
                        }
                    }
                });
        });
    }

    $.fn.message_box = function(type, message, enable_hiding){
        if(!this.length)
            return _W("*fn: message_box(): " + this.selector + " is n/a!");
        enable_hiding = (typeof enable_hiding === 'undefined') ? true : enable_hiding;
        type = (type.indexOf("alert") == -1) ? "alert-" + type : type;
        $("#message_box").remove();
        var hide_text = enable_hiding ? '<br><em style="font-size: 11px;">Click to hide message</em>' : '';
        var message_box = '<div id="message_box" style="display: none;" class="alert '+type+'">' + message + hide_text +'</div>';
        this.prepend(message_box);
        $("#message_box").fadeIn();
        if(enable_hiding){
            $(document).on("click","#message_box",function(){
                $(this).fadeOut();
            });
        }
    }

    $.fn.post_form = function(fn){
        if(!this.length)
            return _W("*fn: post_form(): " + this.selector + " is n/a!");


        var self = this;
        var HREF = self.attr("data-href");
        if(!HREF){
            HREF = location.href;
            _L('*fn: post_form(): data-href is undefined, use current href: "' + HREF + '" instead');
        }
        this.submit(function(e){
            e.preventDefault();
            var data = get_form_data(self.selector);
            $.post(HREF, data)
                .done(function(d){
                    if(d == "SUCCESS"){
                        if(typeof fn == 'function'){
                            fn.call(self, data);
                        }

                    }else{
                        var msg = d.replace(/<br>$/, '');
                        self.message_box("alert-danger", msg);
                    }
                }).fail(function(j, q){error(q)});
        });
        return self;
    }

    $.fn.create_upload_panel = function(fn, button_text){
        if(!this.length)
            return _W("*fn aborted: create_upload_panel(): " + this.selector + " is n/a!");
        button_text =  button_text || 'Tải ảnh lên';
        var self = this;
        var upload_url = self.attr("data-upload-url");
        if(!upload_url)
            return _W("create_upload_panel: please insert data-upload-url attribute!");
        var btn_id = make_id(32);
        var file_input_id = make_id(33);
        var text_id  = make_id(34);
        var bar_id    = make_id(35);

        var upload_btn = ' <a id="' + btn_id+ '"  class="btn btn-primary btn-xs"><span class="glyphicon glyphicon-picture"></span>&nbsp;' + button_text + '</a>';
        var upload_input = '<input name="temporary" type="file" id="' + file_input_id + '"  style="visibility: hidden; width: 1px; height: 1px" />';
        var upload_progress = '<br/><em id="' +text_id + '"></em>';
        var progress_bar = '<div id="' + bar_id +'" class="progress" style="display: none;height: 10px; width: 200px;"> <div  class="progress-bar progress-bar-success" style="width: 0%;"></div></div>';
        self.append(upload_btn + upload_input + upload_progress + progress_bar);


        $(document).on("click", "#" + btn_id,function(){
            $("#" + file_input_id).click();
        });
        $(document).on("change", "#" + file_input_id, function(){
            var file = this.files[0];
            //
            if(["image/jpeg", "image/png","image/jpg"].indexOf(file.type) == -1){
                alert("Chỉ chấp nhận .JPEG, .JPG, .PNG")
                return;
            }
            if(file.size > 1048576){
                alert("Kích thước file " + file.size+" > 1048576 (1MB)");
                return;
            }

            var xhr = new XMLHttpRequest();
            if (xhr.upload) {
                var progress = self.get(0);/*document.body.appendChild(document.createElement("p"));*/
                // progress bar
                xhr.upload.addEventListener("progress", function(e) {
                    var pc = parseInt(e.loaded / e.total * 100);
                    $("#" + bar_id).show();
                    $("#" + text_id).text("Uploading: " + pc + " %");
                    $("#" + bar_id + " .progress-bar").css('border-radius', '3px');
                    $("#" + bar_id + " .progress-bar").css("width", pc+"%");
                }, false);


                // file received/failed
                xhr.onreadystatechange = function(e) {
                    if (xhr.readyState == 4) {
                        if(xhr.status == 200){
                            //console.log(xhr.responseText);
                            $("#" + text_id).text("Upload success!");
                            //var ret_img = "http://" + location.hostname + webroot + get_ajax_tag("src", xhr.responseText);
                            if(typeof fn == 'function')
                                fn.call(self, xhr.responseText); //xhr.responseText
                        }
                    }
                };

                // start upload
                xhr.open("POST", upload_url, true);
                //xhr.setRequestHeader("X_ALBUM_ID",album_id);
                xhr.setRequestHeader("X_FILENAME", file.name);
                xhr.send(file);


            }
        });
        return self;
    }

    $.fn.create_date_picker   = function(){
        if(!this.length)
            return _W("create_date_picker(): " + this.selector + " is n/a!");

    }
})(window.jQuery)

function pr(object){
    //print raw level 1 object
    var output = '';
    for (var p in object) {
        output += p + ' => ' + object[p]+'\n ';
    }
    console.log(output);
    //return output;
}

function make_id(len){
    len = len || 5;
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < len; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function get_param_by_name(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function error(q){
    alert("Có lỗi không xác định!");
    console.warn(q);
}

function _W(s){
    console.warn(s);
    return false;
}

function _L(s){
    console.log(s);
    return true;
}

function is_mobile(){
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function number_format(n, c, d, t){
    var
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function add_route(href, fn){
    if(location.href.indexOf(href) != -1){
        fn.call();
    }
}

function get_ajax_tag(tag_name, s){
    var m = s.match(new RegExp('<' + tag_name + '>(.*?)<\/' + tag_name + '>'));
    return (m) ? m[1] : '';
}

function get_form_data(form_selector){
    var  data = {};
    var index = 1;
    //get input data
    $(form_selector + " input").each(function(){
        var name = $(this).attr("name");
        var type = $(this).attr("type");
        if(!name) throw("#err: Expected name attribute at input no." + index);
        if(!type) throw("#err: Expected type attribute at input no." + index);
        index++;
        if(type == "file")
            return true;
        if(type == "checkbox"){
            data[name] = $(form_selector + ' input[name="' + name + '"]').is(":checked") ? 1 : 0;
            return true;
        }
        if(type == "radio"){
            data[name] = $(form_selector + ' input[name="' + name + '"]:checked').val();
            return true;
        }

        data[name] = $(this).val();
    });
    //get select data
    index = 1;
    $(form_selector + " select").each(function(){
        var name = $(this).attr("name");
        if(!name) throw("#err: Expected name attribute at select no." + index);
        data[name] = $(this).val();
        index++;

    });
    //get text area data
    index = 1;
    $(form_selector + " textarea").each(function(){
        var name = $(this).attr("name");
        if(!name) throw("#err: Expected name attribute at textarea no." + index);
        data[name] = $(this).val();
        index++;
    });
    //pr(data);
    return data;
}

